#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 18:03
# @Author  : Tom_zc
# @FileName: majun_helper.py
# @Software: PyCharm
import base64
import hashlib
import hmac
import time
import logging
import requests

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class LiBingHelper:
    add_repo_url = "{}/gateway/openlibing-framework/project-repo/external/add-repo"

    repo_exist_failed_code = "the repo already existed"

    def __init__(self, accountId, app_token, domain):
        self.accountId = accountId
        self.appKey = app_token
        self.domain = domain

    def refresh_sign(self, timestamp):
        hmac_string = self.accountId + timestamp
        hmac_hash = hmac.new(self.appKey.encode(), hmac_string.encode(), digestmod=hashlib.sha256)
        hmac_base64 = base64.b64encode(hmac_hash.digest()).decode()
        return hmac_base64

    def add_repo(self, gitcode_domain, org, repo_name, private):
        timestamp = str(int(time.time() * 1000))
        headers = {
            "User-Agent": '',
            "Content-Type": "application/json",
            "accountid": self.accountId,
            "timestamp": timestamp,
            "sign": self.refresh_sign(timestamp)
        }
        data = {
            "projectName": "openUBMC",
            "repoName": repo_name,
            "repoUrl": "{}/{}/{}.git".format(gitcode_domain, org, repo_name),
            "repoOwner": "testADD",
            "platform": "gitcode",
            "purpose": "构建",
            "visibility": "私有" if private.lower() == "private" else "外部开源",
            "repoLanguage": "LUA",
            "repoBranchDTOS": []
        }
        logging.info("data is:{}".format(data))
        resp = requests.post(self.add_repo_url.format(self.domain), json=data, headers=headers)
        logging.info("resp is:{}".format(resp))
        if str(resp.status_code).startswith("20"):
            logging.info("resp is:{}".format(resp.text))
            return resp
        logging.info("add repo failed, and reason is:{}".format(str(resp)))
        return